package org.dandsoft.blackbox.utils.table;

import org.dandsoft.blackbox.utils.list.ListElement;
import org.dandsoft.blackbox.utils.list.ListElementIterator;

/**
 * @author Vilyuzhanin Denis (Fin)
 */
public class Cell {

    private long keyRow;
    private long keyColumn;
    private Object data;
    private ListElement<Cell> rowList = new ListElement<Cell>(this);
    private ListElement<Cell> columnList = new ListElement<Cell>(this);


    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public long getRowKey() {
        return keyRow;
    }

    public void setRowKey(long keyRow) {
        this.keyRow = keyRow;
    }

    public long getColumnKey() {
        return keyColumn;
    }

    public void setColumnKey(long keyColumn) {
        this.keyColumn = keyColumn;
    }

    public synchronized boolean isDisconnected() {
        return rowList.isDisconnected() && columnList.isDisconnected();
    }

    public ListElementIterator<Cell> getRowListIterator() {
        return new ListElementIterator<Cell>(rowList);
    }

    public ListElementIterator<Cell> getColumnListIterator() {
        return new ListElementIterator<Cell>(columnList);
    }


    public synchronized void connectToRow(Cell cell) {
        synchronized (cell) {
            cell.rowList.connectOnRight(rowList);
            this.keyRow = cell.keyRow;
        }
    }

    public synchronized void connectToColumn(Cell cell) {
        synchronized (cell) {
            cell.columnList.connectUnder(columnList);
            this.keyColumn = cell.keyColumn;
        }
    }

    public synchronized void disconnect() {
        rowList.remove();
        columnList.remove();
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("Cell");
        sb.append("{data=").append(data);
        sb.append(", keyRow=").append(keyRow);
        sb.append(", keyColumn=").append(keyColumn);
        sb.append('}');
        return sb.toString();
    }
}
